const fs = require('fs')
const fse = require('fs-extra')

/**
 * 根据后缀筛出指定文件夹下的所有文件
 * @param {string} dir 源目录
 * @param {string[] = []} exts 后缀名列表
 * @param {string} target 输出目录
 */
function filterFileByExt(dir, exts = [], target) {
  const files = fs.readdirSync(dir)
  for (let i = 0, len = files.length; i < len; i++) {
    const item = files[i]
    const stat = fs.lstatSync(`${dir}/${item}`)
    if (stat.isDirectory()) {
      filterFileByExt(`${dir}/${item}`, exts, `${target}/${item}`)
    } else {
      for (let j = 0; j < exts.length; j++) {
        let ext = exts[j]
        if (item.split('.').pop().toLowerCase() === ext.trim().toLowerCase()) {
          try {
            const source = `${dir}/${item}`
            const dest = `${target}/${item}`
            fse.copySync(source, dest)
            // console.log(`[success!]: copy ${source} -> ${dest}`)
          } catch (err) {
            console.log(`[failed!]: copy ${source} -> ${dest}`)
            console.error(err)
          }
          break
        }
      }
    }
  }
}

const RNOH_PATH = '../third_party/ohos_react_native/tester/harmony/react_native_openharmony'
const MAIN_PATH = `${RNOH_PATH}/src/main`

// [1] 修改 rnoh CMakeLists.txt
fs.readFile(`${MAIN_PATH}/cpp/CMakeLists.txt`, 'utf8', (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  // 替换
  const replaceData = data
    .replace(/\bset\b/, `project(rnoh_semi)\nset(RNOH_CPP_DIR "\${CMAKE_CURRENT_SOURCE_DIR}")\nset`)
    .replace(/\badd_compile_options\b/, `set(WITH_HITRACE_SYSTRACE 1)\nadd_compile_definitions(WITH_HITRACE_SYSTRACE)\nadd_compile_options`)
    .replace(/\brnoh\b/g, 'rnoh_semi')
    .replace(/if\(\"\$ENV\{RNOH_C_API_ARCH\}\" STREQUAL \"1\"\)([\s\S]*?)endif\(\)/, '$1')
  // 写入
  fs.writeFile(`${MAIN_PATH}/cpp/CMakeLists.txt`, replaceData, 'utf8', err => {
    if (err) {
      console.error(err)
      return
    }
  })
})

// [2] 替换 rnoh build-profile
fse.copySync('./build-profile.json5', `${RNOH_PATH}/build-profile.json5`)

// [3] 补充 RNOHOther
fse.copySync('./RNOHOther.cpp', `${MAIN_PATH}/include/RNOHOther.cpp`)

// [4] 筛出所有头文件
filterFileByExt(`${MAIN_PATH}/cpp`, ['h', 'hpp', 'ipp'], `${MAIN_PATH}/include`)

// [5] 同步其他文件
const sourceList = [
  'third-party/folly/CMake/folly-config.h.cmake',
  'third-party/folly/folly/lang/SafeAssert.cpp',
  'RNOHAppNapiBridge.cpp',
]
sourceList.forEach(filePath => {
  try {
    fse.copySync(`${MAIN_PATH}/cpp/${filePath}`, `${MAIN_PATH}/include/${filePath}`)
    // console.log(`[success!]: copy ${MAIN_PATH}/cpp/${filePath} -> ${MAIN_PATH}/include/${filePath}`)
  } catch (err) {
    console.log(`[failed!]: copy ${MAIN_PATH}/cpp/${filePath} -> ${MAIN_PATH}/include/${filePath}`)
    console.error(err)
  }
})
